package com.joe.security.distributed.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nimbusds.jose.JWSObject;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URLEncoder;

/**
 * @Description
 * @Author 高建伟-joe
 * @Date 2023-11-10
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();

        // 非JWT放行不做后续解析处理
        String token = request.getHeaders().getFirst("Authorization");
        if (StringUtils.isBlank(token) || !StringUtils.startsWithIgnoreCase(token, "Bearer ")) {
            return chain.filter(exchange);
        }

        // 解析JWT
        token = StringUtils.replace(token, "Bearer ", Strings.EMPTY);
        String payload = JSON.toJSONString(JSON.parse(JWSObject.parse(token).getPayload().toString()));

        // request写入JWT的载体信息
        request = exchange.getRequest().mutate()
                .header("payload", URLEncoder.encode(payload, "UTF-8"))
                .build();
        exchange = exchange.mutate().request(request).build();
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
